from qtDesigner.ui_advertiseWidget import Ui_Form
from PyQt5.QtWidgets import QApplication, QWidget, QFileDialog
from PyQt5.QtGui import QPixmap, QCursor
from PyQt5.QtCore import Qt
from Dialog import FileDialog, WarningMessageBox
from handler.advertiseHandle import advertiseHandle
import requests
from base64 import b64decode, b64encode
import cv2
import numpy as np
import sys
import time

sec = requests.session()

class advertiseWidget(Ui_Form, QWidget):
    def __init__(self, parent=None):
        super(advertiseWidget, self).__init__(parent=parent)
        self.setupUi(self)
        self.handle = advertiseHandle()
        self.picData = dict()

        self.selectPicBtn1.clicked.connect(self.on_selectBtn)
        self.selectPicBtn2.clicked.connect(self.on_selectBtn)
        self.selectPicBtn3.clicked.connect(self.on_selectBtn)
        self.BannerBtn.clicked.connect(self.on_BannerBtn)
        self.NoticeBtn.clicked.connect(self.on_NoticeBtn)
        self.selectPicBtn1.setProperty("class", "advertiseBtn")
        self.selectPicBtn2.setProperty("class", "advertiseBtn")
        self.selectPicBtn3.setProperty("class", "advertiseBtn")
        self.BannerBtn.setProperty("class", "advertiseBtn")
        self.NoticeBtn.setProperty("class", "advertiseBtn")
        #self.display()

    def on_selectBtn(self):
        if self.sender().objectName() == "selectPicBtn1":
            self._uplaodPic(self.BannerLabel1)
        elif self.sender().objectName() == "selectPicBtn2":
            self._uplaodPic(self.BannerLabel2)
        elif self.sender().objectName() == "selectPicBtn3":
            self._uplaodPic(self.BannerLabel3)

    def _get_imgs(self, img_list, img_names):
        ret = list()
        for each in range(img_names.__len__()):
            if img_list[each].startswith("http"):
                try:
                    file = sec.get(img_list[each])
                    img = cv2.imdecode(np.fromstring(file.content, np.uint8), 1)
                    imgname = './temp/' + img_names[each]
                    ret.append(imgname)
                    cv2.imwrite(imgname, img)
                except Exception as e:
                    print(e)
                    return False, None
            elif each == "请点击插入图片":
                pass
            else:
                url = img_list[each].encode("utf-8")
                image_data = b64decode(url)
                img = cv2.imdecode(np.fromstring(image_data, np.uint8), 1)
                imgname = './temp/' + img_names[each]
                ret.append(imgname)
                cv2.imwrite(imgname, img)

        return True, ret

    def on_BannerBtn(self):
        imgs_list = list()
        name_list = list()
        for each in self.picData.keys():
            name_list.append("Banner" + each[-1:] + ".jpg")
            imgs_list.append(self.picData[each])
        self._get_imgs(imgs_list, name_list)
        status, res = self.handle.upload_banners(name_list)
        print(res)
        if not status:
            WarningMessageBox("图片上传失败，服务器异常").exec()

    def on_NoticeBtn(self):
        data = dict()
        data["remark"] = ""
        data["status"] = 0
        data["create_by"] = "yixianshenji"
        data["update_by"] = "yixianshenji"
        data["notice_content"] = self.NoticeText.toPlainText()
        status, ret = self.handle.upload_notice(data)

        if not status:
            WarningMessageBox("消息上传失败，服务器异常").exec()

    def _displayimg(self, url, label):
        pix = QPixmap()
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        if url.startswith("http"):
            start = time.time()
            i = 0
            QApplication.processEvents()
            while i < 1000:
                try:
                    response = requests.get(url, timeout=(2, 0.5))
                    break
                except requests.exceptions.RequestException as e:
                    print(e)
                    i += 1
                    if i == 999:
                        return

            print('time', time.time() - start)
            pix.loadFromData(response.content)
            pix = pix.scaled(label.width(), label.height())
            label.setStyleSheet("border:none")
            label.setPixmap(pix)
            image_byte = b64encode(response.content)
            base64_string = image_byte.decode('utf-8')
            QApplication.restoreOverrideCursor()
            self.picData[label.objectName()] = base64_string
            return base64_string
        elif url == "请点击插入图片":
            label.setText(url)
            label.setStyleSheet("background-color:gray;border: 1px solid black;")
        else:
            url = url.encode("utf-8")
            image_data = b64decode(url)
            pix.loadFromData(image_data)
            pix = pix.scaled(label.width(), label.height())
            label.setStyleSheet("border:none")
            label.setPixmap(pix)
        QApplication.restoreOverrideCursor()
        return None

    def _uplaodPic(self, label):
        fd = FileDialog(QFileDialog.AcceptOpen, "选择图片")
        path = fd.getSelectFilePath()
        if path is not None:
            img = cv2.imdecode(np.fromfile(path, dtype=np.uint8), -1)

            # width = img.shape[1]
            # height = img.shape[0]
            # width_new = 600
            # height_new = 400
            #
            # # 判断图片的长宽比率
            # if width / height >= width_new / height_new:
            #     img_new = cv2.resize(img, (width_new, int(height * width_new / width)))
            # else:
            #     img_new = cv2.resize(img, (int(width * height_new / height), height_new))
            img_new = img

            cv2.imwrite('./temp/temp.jpg', img_new)
            with open('./temp/temp.jpg', "rb") as file:
                image_byte = b64encode(file.read())
            base64_string = image_byte.decode('utf-8')
            self.picData[label.objectName()] = base64_string
            self._displayimg(base64_string, label)

    def display(self):
        self._displayimg("https://www.yixianshenji.com/img/Banner1.jpg", self.BannerLabel1)
        self._displayimg("https://www.yixianshenji.com/img/Banner2.jpg", self.BannerLabel2)
        self._displayimg("https://www.yixianshenji.com/img/Banner3.jpg", self.BannerLabel3)

        status, res = self.handle.show_notice()
        if status:
            self.NoticeText.setPlainText(res["notice"][0]["notice_content"])
            return True
        else:
            WarningMessageBox("数据获取失败，服务器异常").exec()
            return False

def main():
    app = QApplication(sys.argv)

    ui = advertiseWidget()
    ui.show()

    sys.exit(app.exec_())

if __name__ == '__main__':
    main()
